package com.xu.deadLock;

/**
 * 演示死锁的概念
 *  线程A 与线程B 相互持有资源并同时获取对方的资源陷入等待,造成死锁
 */
public class DeadLockDemo1 {
    //创建资源
    private static Object resourceA = new Object();
    private static Object resourceB = new Object();

    public static void main(String[] args) {
        //创建线程A
        Thread threadA = new Thread(() -> {
            synchronized (resourceA) {
                System.out.println(Thread.currentThread() + "get ResourceA");
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + "waiting get ResourceB");
                synchronized (resourceB) {
                    System.out.println(Thread.currentThread() + "get ResourceB");
                }
            }
        });


        //创建线程B
        Thread threadB =  new Thread(()->{
            synchronized (resourceB){
                System.out.println(Thread.currentThread()+"get ResourceB");
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread()+"waiting get ResourceA");
                synchronized (resourceA){
                    System.out.println(Thread.currentThread()+"get ResourceA");
                }
            }
        });
        threadA.start();
        threadB.start();
    }

}
